package com.hs.service.impl;

import com.hs.entity.dto.CommentDTO;
import com.hs.entity.pojo.Comment;
import com.hs.entity.pojo.User;
import com.hs.entity.vo.CommentVO;
import com.hs.mapper.CommentMapper;
import com.hs.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hs.service.UserService;
import com.hs.utils.BeanCopyUtil;
import com.hs.utils.RedisCache;
import com.hs.utils.ResultResponse;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hs
 * @since 2023-08-05
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Resource
    private RedisCache redisCache;

    @Resource
    private UserService userService;

    @Override
    public ResultResponse<List<CommentVO>> getCommentsByTrendId(Integer trendId) {

        // 先获取根评论
        List<Comment> rootComments = query()
                .eq("trend_id", trendId)
                .eq("parent_id", -1)
                .orderByDesc("id").list();

        List<CommentVO> rootCommentVOS = getCommentVOS(rootComments);

        // 再获取子评论
        rootCommentVOS.forEach(root ->{
            Integer rootId = root.getId();
            List<Comment> children = query().eq("trend_id", trendId).eq("parent_id", rootId).orderByDesc("id").list();
            List<CommentVO> childrenCommentVOS = getCommentVOS(children);
            root.setChildren(childrenCommentVOS);
        });

        return ResultResponse.ok(rootCommentVOS);
    }

    @NotNull
    private List<CommentVO> getCommentVOS(List<Comment> comments) {
        return BeanCopyUtil.copyBeanList(comments, CommentVO.class).stream().peek(c -> {
            User createUser = Optional.ofNullable(userService.getById(c.getCreateUserId())).orElseGet(User::new);
            c.setCreateNickName(createUser.getNickName());
            User toUser = Optional.ofNullable(userService.getById(c.getToUserId())).orElseGet(User::new);
            c.setToNickName(toUser.getNickName());
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public ResultResponse<?> publishComment(CommentDTO commentDTO) {
        Comment comment = BeanCopyUtil.copyBean(commentDTO, Comment.class);
        Integer trendId = comment.getTrendId();
        save(comment);
        // redis评论数+1
        redisCache.incrementCacheMapValue("pet:view:trendCommentCount:",trendId.toString(),1);
        return ResultResponse.ok();
    }
}
